// 检测count模块的相关action,进而触发异步请求，将count数据存入数据库
import { takeLatest, call, put } from "redux-saga/effects";
import { IN_CREMENT } from "../actions/count";
import { countPost, countGet, countPut } from "../../api/course";
import store from "../index";
//负责异步请求的函数
function* countSagaPost() {
  console.log("检测到有人在触发IN_CREMENT", store.getState());
  try {
    let res1 = yield call(countGet); //查询
    if (res1.data.results.length) {
      let { objectId } = res1.data.results[0];
      yield call(countPut, objectId, store.getState().count); //更新
    } else {
      yield call(countPost, store.getState().count); //将100发送给异步请求的countPost函数，让countPost发往后端
    }
  } catch (error) {}
}

// 触发action检测的函数
export default function* countSaga() {
  yield takeLatest(IN_CREMENT, countSagaPost);
}
